package com.example.linked;

public class Leetcode61_RotateRight {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
//        node3.next = node4;
//        node4.next = node5;

        // [1,2,3]
        // 2000000000

        ListNode res = new Solution().rotateRight(node1, 2);
        ListNode cur = res;
        while (cur != null) {
            System.out.println(cur.val);
            cur = cur.next;
        }

    }

    static class Solution {
        /**
         * 先将链表形成循环链表
         * 然后找到合适的地方破环
         * @param head
         * @param k
         * @return
         */
        public ListNode rotateRight(ListNode head, int k) {
            if (head == null || head.next == null || k == 0) return head;
            ListNode cur = head;
            // 1 -> 2 -> 3 -> 4 -> 5
            // 4 -> 5         1 -> 2 -> 3
            // 4 -> 5 -> 1 -> 2 -> 3

            // 1 2 3
            // 2 3 1
            int count = cur == null ? 0 : 1;
            while (cur != null && cur.next != null) {
                count++;
                cur = cur.next;
            }
            ListNode tail = cur;

            int rotateCount = count - k % count;
            if (rotateCount == count) return head;
            tail.next = head;
            for (int i = rotateCount; i > 0; i--) {
                cur = cur.next;
            }

            ListNode res = cur.next;
            cur.next = null;
            return res;
        }
    }
}
